<?php
namespace Library;

use Phalcon\Logger\Adapter\File as FileAdapter;

trait Helper
{

    protected $logger;

    /**
     * 开启日志事物
     * @param string $method
     */
    public function writeLogStart($method = 'post', $msg = '')
    {
        if (!$this->getDI()->get('config')->debug) return false;
        defined('NOWUNID') ? NOWUNID : define('NOWUNID', date('y-m-d H:i:s') . '_' . rand(1, 1000));
        $filename = APP_PATH . '/data/' . $method . '.log';
        if (!is_file($filename)) {
            touch($filename);
        }
        $this->logger = new FileAdapter($filename);
        $this->logger->begin();
        $this->logger->alert($msg . NOWUNID);
        $this->logger->alert("#########################");
    }

    /**
     * 写日志
     * @param string $data
     * @return boolean
     */
    public function writeLog($data = '')
    {

        if (!$this->getDI()->get('config')->debug) return false;
        if (is_array($data) || is_object($data)) {
            $data = var_export($data, true);
        }
        $this->logger->info($data);
        if (defined('SHELL') && SHELL === 'php') {
            $this->submit();
        }
    }

    /**
     * 统一输出
     * @param array $d
     * @param bool $debug
     *
     */
    protected function e($d, $debug = false)
    {
        if ($debug) {
            var_dump($d);
            throw new  \Exception ();
        }
        header('Content-Type:application/json; charset=utf-8');
        if (!is_array($d)) {
            $d = ['msg' => '', 'status' => 0, 'code' => '', 'data' => ''];
        }
        $d['data'] = empty($d['data']) ? $d['data'] = new \stdClass() : $d['data'];
        $this->writeLogStart($this->dispatcher->getControllerName(), '返回值:');
        $this->writeLog($d);
        $msg = json_encode($d);

        if (defined('SHELL') && SHELL === 'php') {

            throw new  \Exception ($msg);
        } else {
            die($msg);
        }
    }

    /**
     * 生成密码
     * @param string $name
     * @param string $pwd
     */
    protected function md5($name = '', $pwd = '')
    {
        $str = $name . $pwd . $this->config->pwd;
        $str = md5(sha1($str));
        return $str;
    }

    /**
     * 生成token
     */
    protected function token()
    {
        $pid = getmypid();//进程id,解决高并发
        time_nanosleep(0, 1000);//延时1000纳秒=1毫秒,解决同一进程同时连续多次调用
        $timetick = microtime(TRUE) * 1000;//微秒
        $uuid = hash('ripemd160', $pid . '+' . $timetick);
        return $uuid;
    }

    /**
     * 生成短信验证码
     */
    protected function createCode()
    {
        $num = '';
        for ($i = 0; $i < 4; $i++) {
            $num .= mt_rand(0, 9);
        }
        return $num;
    }

    /**
     * rsa 解密
     * @return array|string:
     */
    protected function post($debug = false)
    {

        $this->writeLogStart($this->dispatcher->getControllerName(), '接收值:');
        if ($this->getDI()->get('config')->requestDebug) {
            $data = $this->request->get();

            $this->writeLog($data);
            return $data;
        }
        if ($debug) {
            $data = $this->request->get('d');
        } else {
            $rsa = new \Library\Rsa();
            $data = $this->request->getPost('d');
            $data = $rsa->partPrivDecrypt($data);
        }
        $dataJSON = @json_decode($data, true);
        $this->writeLog($dataJSON ? $dataJSON : $data);
        return $dataJSON ? $dataJSON : $data;

    }

    public function __destruct()
    {
        if ($this->logger) {
            $this->logger->alert("@@@@@@@@@@@@@@@@@@@@@@@@\n");
            $this->logger->commit();
        }
    }

    public function submit(){
        if ($this->logger) {
            $this->logger->alert("@@@@@@@@@@@@@@@@@@@@@@@@\n");
            $this->logger->commit();
        }
    }
}

?>